package com.dmgis.qxfw.dataservice.businessservice.yydl.controller;

import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.township_station;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.TownShipStation;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.HourTemp;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.MsgMedium;
import com.dmgis.qxfw.dataservice.businessservice.common.util.DateTime;
import com.dmgis.qxfw.dataservice.businessservice.yydl.service.HourTempServiceI;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/xtdl")
public class HourTempController {

	@Autowired
	private HourTempServiceI hourTempServiceImpl;

	@Resource
	private ITransformService transformService;



	String temp = "";

	@RequestMapping("/loadCountyPower")
	@ResponseBody
	public String loadCountyPower() {
		temp = "[";
		temp += "{\"text\":\"全部\",\"value\":\"\"},";
		List<String> list = hourTempServiceImpl.loadCountyPower();
		for (String s : list) {
			temp += "{\"text\":\"" + s + "\",\"value\":\"" + s + "\"},";
		}
		if (temp.length() > 1) {
			temp = temp.substring(0, temp.length() - 1);
		}
		temp = temp + "]";
		return temp;
	}

	@RequestMapping(value={"/mapHourTemperature","mapHourTemperatureWX"})
	@ResponseBody
	public List<HourTemp> mapHourTemperature(HttpServletRequest request) throws Exception {
		List<HourTemp> listResult = new ArrayList<HourTemp>();

		// 1. 参数校验
		if(request.getParameter("dateTime") == null || request.getParameter("Hour") == null) {
			return listResult;
		}

		// 2. 初始化参数
		String strDateTime = request.getParameter("dateTime");
		DateTime dateTime = DateTime.parseDateTime(strDateTime);
		int hour = Integer.valueOf(request.getParameter("Hour"));
		String strDate1 = dateTime.AddHours(hour).toDateTimeString();
		String strDate2 = dateTime.AddHours(hour).AddHours(11).toDateTimeString();
		hour = dateTime.AddHours(hour).GetHour(); // 起报时间

		// 3. 获取站点列表
		List<township_station> list = new ArrayList<township_station>();
		boolean isWxRequest = request.getRequestURI().equals("/xtproweb/xtdl/mapHourTemperatureWX");

		if(isWxRequest) {
			String wxId = request.getParameter("city");
			if(wxId != null && !wxId.isEmpty()) {
				township_station t = new township_station();
				t.setStationid(wxId);
				list.add(t);
			}
		} else {
			list = hourTempServiceImpl.getStationId("N6077", "N6327");
		}

		// 4. 处理每个站点数据
		int index = 0;
		for (township_station t : list) {
			String stationID = t.getStationid();

			// 获取预报和实况数据
			List<TownShipStation> dat = hourTempServiceImpl.getTownShipStation(strDate1, strDate2, stationID);
			List<MsgMedium> skDat = hourTempServiceImpl.getMsgMediumSmallScaleTemp(
					stationID,
					dateTime.AddHours(hour).AddHours(-12).toDateTimeString(),
					dateTime.AddHours(hour - 1).toDateTimeString()
			);

			if (dat.isEmpty()) continue;

			// 构建HourTemp对象
			HourTemp ht = new HourTemp();
			ht.setStationId(stationID);
			if(!isWxRequest) {
				ht.setStationName(t.getStationname());
				double x = t.getLongitude();
				double y = t.getLatitude();
				ht.setLon(x);
				ht.setLat(y);
				DmMapPoint dmDot = new DmMapPoint(x, y);
				DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
				ht.setY(ltDot.y);
				ht.setX(ltDot.x);
			}
			ht.setChartId("temp" + (index++));

			// 构建图表数据
			StringBuilder xValue = new StringBuilder("[");
			StringBuilder skTempVal = new StringBuilder("[");
			StringBuilder tempVal = new StringBuilder("[");
			StringBuilder humidVal = new StringBuilder("[");
			StringBuilder humidVal1 = new StringBuilder("[");

			// 处理实况数据
			for (MsgMedium msg : skDat) {
				DateTime time = new DateTime(msg.getObservTime());
				String tempH = msg.getRelHumidity();
				String tempe = msg.getDryBulbTemp();
				tempe = tempe == null || tempe.isEmpty() ? "0" : tempe;

				xValue.append("'").append(time.GetHour()).append("',");
				skTempVal.append(tempe).append(",");
				tempVal.append("null").append(",");
				humidVal1.append(tempH).append(",");
				humidVal.append("null").append(",");
			}

			// 处理预报数据
			for (TownShipStation ts : dat) {
				DateTime time = new DateTime(ts.getDateTime());
				String tempe = String.format("%.1f", ts.getTemperature());
				String tempH = String.format("%.1f", ts.getHumid());

				if (time.GetHour() == hour) {
					ht.setTemp(tempe);
					ht.setHumid(tempH);
				}

				xValue.append("'").append(time.GetHour()).append("',");
				tempVal.append(tempe).append(",");
				humidVal.append(tempH).append(",");
				skTempVal.append("null").append(",");
				humidVal1.append("null").append(",");
			}

			// 构建最终数据字符串
			if (xValue.length() > 1) xValue.setLength(xValue.length() - 1);
			if (skTempVal.length() > 1) skTempVal.setLength(skTempVal.length() - 1);
			if (tempVal.length() > 1) tempVal.setLength(tempVal.length() - 1);
			if (humidVal.length() > 1) humidVal.setLength(humidVal.length() - 1);
			if (humidVal1.length() > 1) humidVal1.setLength(humidVal1.length() - 1);

			ht.setxValue(xValue.append("]").toString());
			ht.setyValue(new StringBuilder("[")
					.append(skTempVal).append("],")
					.append(tempVal).append("],")
					.append(humidVal).append("],")
					.append(humidVal1).append("]]").toString());

			listResult.add(ht);
		}

		return listResult;
	}


	/*@RequestMapping(value={"/mapHourTemperature","mapHourTemperatureWX"})
	@ResponseBody
	public List<HourTemp> mapHourTemperature(HttpServletRequest request) throws Exception {
		String strDateTime = "";
		List<HourTemp> listResult = new ArrayList<HourTemp>();
		if(request.getParameter("dateTime")!=null){
			strDateTime = request.getParameter("dateTime");
			DateTime dateTime = DateTime.parseDateTime(strDateTime);
			int hour = Integer.valueOf(request.getParameter("Hour"));
			String strDate1 = dateTime.AddHours(hour).toDateTimeString();
			String strDate2 = dateTime.AddHours(hour).AddHours(11).toDateTimeString();

			hour = dateTime.AddHours(hour).GetHour();// 起报时间
			// 获取id
			List<township_station> list = new ArrayList<township_station>();

			//判断是否是微信来的请求
			String uri = request.getRequestURI();
			boolean flag = false;
			if(uri.equals("/xtproweb/xtdl/mapHourTemperatureWX")){
				flag = true;
				String wxId = request.getParameter("city");
				township_station t = new township_station();
				if(wxId!=null&&wxId.length()>0){
					t.setStationid(wxId);
					list.add(t);
				}
			}else{
				list = hourTempServiceImpl.getStationId("N6077", "N6327");
			}
			double x=0, y=0;
			String xValue, yValue;
			DateTime time;
			int index = 0;
			// 循环查询每个id
			for (township_station t : list) {
				String stationID = t.getStationid();
				//预报
				List<TownShipStation> dat = hourTempServiceImpl.getTownShipStation(strDate1, strDate2, stationID);
				//实况
				List<MsgMedium> skDat = hourTempServiceImpl.getMsgMediumSmallScaleTemp(stationID,
						dateTime.AddHours(Integer.valueOf(request.getParameter("Hour"))).AddHours(-12).toDateTimeString(),
						dateTime.AddHours(Integer.valueOf(request.getParameter("Hour"))- 1).toDateTimeString());
				if (dat.isEmpty())
					continue;
				HourTemp ht = new HourTemp();
				ht.setStationId(stationID);
				if(!flag){
					ht.setStationName(t.getStationname());
					x = t.getLongitude();
					y = t.getLatitude();
					ht.setLon(x);
					ht.setLat(y);
					DmMapPoint dmDot = new DmMapPoint(t.getLongitude(), t.getLatitude());
					DmMapPoint ltDot = transformService.LonLatConvertToLambert(dmDot.x, dmDot.y);
					ht.setY(ltDot.y);
					ht.setX(ltDot.x);
				}
				ht.setChartId("temp" + (index++));
				xValue = "[";
				yValue = "[";
				String humidVal = "[";
				String humidVal1 = "[";
				String tempVal = "[";
				String skTempVal = "[";
				for (MsgMedium msg : skDat) {
					time = new DateTime(msg.getObservTime());
					String tempH = msg.getRelHumidity();
					String tempe = msg.getDryBulbTemp();
					tempe = tempe == "" ? "0" : tempe;
					xValue += "'" + time.GetHour() + "',";
					skTempVal += tempe + ",";
					tempVal += "null" + ",";
					humidVal1 += tempH + ",";
					humidVal += "null" + ",";

				}
				for (TownShipStation ts : dat) {
					time = new DateTime(ts.getDateTime());
					String tempe = String.format("%.1f", ts.getTemperature());
					String tempH = String.format("%.1f", ts.getHumid());
					tempe = tempe == "" ? "0" : tempe;
					if (time.GetHour() == hour) {
						ht.setTemp(tempe);
						ht.setHumid(tempH);
					}
					xValue += "'" + time.GetHour() + "',";
					tempVal += tempe + ",";
					humidVal += tempH + ",";
					skTempVal += "null" + ",";
					humidVal1 += "null" + ",";
				}
				if (xValue.length() > 1) {
					xValue = xValue.substring(0, xValue.length() - 1);
				}
				xValue = xValue + "]";
				if (skTempVal.length() > 1) {
					skTempVal = skTempVal.substring(0, skTempVal.length() - 1);
				}
				if (tempVal.length() > 1) {
					tempVal = tempVal.substring(0, tempVal.length() - 1);
				}
				if (humidVal.length() > 1) {
					humidVal = humidVal.substring(0, humidVal.length() - 1);
				}
				if (humidVal1.length() > 1) {
					humidVal1 = humidVal1.substring(0, humidVal1.length() - 1);
				}
				yValue += skTempVal + "]," + tempVal + "]," + humidVal + "]," +  humidVal1 +"]]";
				ht.setxValue(xValue);
				ht.setyValue(yValue);
				listResult.add(ht);
			}
		}

		return listResult;
	}
*/

	/**
	 * 气象要素最新
	 *
	 * @return
	 */
	@RequestMapping("/yaosuInitTime")
	@ResponseBody
	public List<Object> liveInitTime() {
		ArrayList<Object> objects = new ArrayList<>();
		Date dt = hourTempServiceImpl.liveInitTime();
		DateTime date = new DateTime(dt);
		objects.add(date.toDateTimeString());
		return objects;
	}

}
